package com.zkingsoft.actions.admin;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.config.Dictionary;
import com.zkingsoft.model.Count;
import com.zkingsoft.model.PaginationVO;
import com.zkingsoft.model.Role;
import com.zkingsoft.model.Userdata;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.CountService;
import com.zkingsoft.services.RoleService;
import com.zkingsoft.services.UserdataService;
import com.zkingsoft.services.UsersService;

/**
 * @description 企业管理员管理action
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@Controller
@RequestMapping(value = "admin")
public class CompanyAdminController extends BaseController {

	@Resource
	private UsersService currentService;
	@Resource
	private RoleService roleService;
	@Resource
	private CountService countService;
	@Resource
	private UserdataService userdataService;
	/**
	 * 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "admin/" + page1 + "/" + page2;
	}

	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "admin/" + page1;
	}

	/**
	 * 功能跳转使用的action
	 * 
	 * @param page1
	 * @param page2
	 * @return
	 */
	@RequestMapping(value = "/functionRedirect/{page1}/{fnId}")
	public String functionRedirect(@PathVariable("page1") String page1, @PathVariable("fnId") String fnId,
			HttpServletRequest request) {
		request.setAttribute("fnId", fnId);
		return "admin/" + page1;
	}
	/**
	 * 个人信息显示
	 */
	@RequestMapping(value = "/functionRedirect/personalInfo/{fnId}")
	public String functionRedirectpersonalInfo( @PathVariable("fnId") String fnId,
			HttpServletRequest request) {
		request.setAttribute("fnId", fnId);
		Users admin=(Users) getSession().getAttribute("user");
		Role role = new Role();
		role.setCompanyId(getMe(request).getCompanyId());
		List<Role> list = roleService.findByModel(role);
		request.setAttribute("list", list);
		request.setAttribute("obj", admin);
		return "admin/personalInfo" ;
	}
	/**
	 * 用户管理数据显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(HttpServletRequest request, Users admin, PaginationVO pageVo) {

		admin.setValid(1);
		admin.setCompanyId(getMe(request).getCompanyId());
		admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		return showList(currentService, admin, pageVo);
	}
	/**
	 * 一级代理商数据显示
	 */
	@RequestMapping(value = "/shop1showList")
	public @ResponseBody AjaxResult shop1showList(HttpServletRequest request, Users admin, PaginationVO pageVo) {

		admin.setValid(1);
		admin.setCompanyId(getMe(request).getCompanyId());
		admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		admin.setRoleId((long)19);
		
		return showList(currentService, admin, pageVo);
	}
	/**
	 * 二级代理商数据显示
	 */
	@RequestMapping(value = "/shop2showList")
	public @ResponseBody AjaxResult shop2showList(HttpServletRequest request, Users admin, PaginationVO pageVo) {

		admin.setValid(1);
		admin.setCompanyId(getMe(request).getCompanyId());
		admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		admin.setRoleId((long)20);
		Users user = (Users) getSession().getAttribute("user");
		admin.setParentUserId(user.getId());
		return showList(currentService, admin, pageVo);
	}
	/**
	 * 添加或更新
	 */
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(HttpServletRequest request, Users admin) {
		// 判断去重
		if(admin.getId()==null){
			if (currentService.checkIsAccountRepeat(admin)) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "操作失败，账号已经存在！");
			} else if (currentService.checkIsEmailRepeat(admin)) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "操作失败，邮箱已经存在！");
			}
		}
		
		try {
			if (admin.getPassword() != null) {
				admin.setPassword(EncrypUtil.getMD5(admin.getPassword()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (admin.getId() != null) {
			double quota = currentService.findById(admin.getId()).getQuota();
			Long chargeQuota = admin.getQuota();
			if(chargeQuota!=quota){
				Users user = (Users) getSession().getAttribute("user");
				if(user.getRoleId()!=null){
					if((chargeQuota-quota)<0){
						return new AjaxResult(AjaxResult.STATUS_ERR,null,"您不能扣除额度，请联系客服进行操作！");
					}
				}
				//操作时间
				Date time = new Date();
				if(user.getRoleId()!=null){
					if(user.getRoleId()==19){
						if(chargeQuota>quota){
							Count count = new Count();
							if((user.getQuota()-(chargeQuota-quota))>0){
								user.setQuota((long)(user.getQuota()-(chargeQuota-quota)));
							}else {
								return new AjaxResult(AjaxResult.STATUS_ERR,null,"您的余额不足！");
							}
							currentService.modify(user);
							count.setTime(time.getTime());
							//修改后的钻石
							count.setChargeQuota(user.getQuota());
							//代理商ID
							count.setUsersId(user.getId());
							count.setChargeQuotas("-"+(chargeQuota-quota));
							count.setChargeMoney("+"+(chargeQuota-quota)/user.getProportion());
							countService.add(count);
						}
					}
				}
				Count count = new Count();
				count.setTime(time.getTime());
				//修改后的钻石
				count.setChargeQuota(chargeQuota);
				//代理商ID
				count.setUsersId(admin.getId());
				if(chargeQuota>quota){
					count.setChargeQuotas("+"+(chargeQuota-quota));
					count.setChargeMoney("-"+(chargeQuota-quota)/admin.getProportion());
				}else if(chargeQuota<quota){
					count.setChargeQuotas("-"+(quota-chargeQuota));
					count.setChargeMoney("+"+((quota-chargeQuota)/admin.getProportion()));
				}
				countService.add(count);
			}
			return modify(currentService, admin, "管理员");
		} else {
			admin.setCompanyId(getMe(request).getCompanyId());
			admin.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
			// 加密密码
			admin.setAccountStatus(Dictionary.ACCOUNT_STATUS_ACTIVATE);
			admin.setRegisterTime(new Date());
			admin.setValid(1);
			Users user = (Users) getSession().getAttribute("user");
			admin.setParentUserId(user.getId());
			Users u = new Users();
			if(user.getRoleId()!=null){
				if((user.getQuota()-admin.getQuota())>0){
					u.setQuota(user.getQuota()-admin.getQuota());
					currentService.modify(u);
				}else{
					return new AjaxResult(AjaxResult.STATUS_ERR,null,"您的余额不足！");
				}
				
			}
			return add(currentService, admin, "管理员");
		}
	}
	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {

		return remove(currentService, keys);
	}
	/**
	 * 用户管理弹出框数据显示
	 */
	@RequestMapping(value = "/editForm")
	public String editForm(Long id, HttpServletRequest request) {
		Users admin;
		Role role = new Role();
		role.setCompanyId(getMe(request).getCompanyId());
		List<Role> list = roleService.findByModel(role);
		request.setAttribute("list", list);
		if (id != null) {
			admin = currentService.findById(id);
			request.setAttribute("obj", admin);
		}
		return "admin/admin-form";
	}
	/**
	 * 一级代理商弹出框数据显示
	 */
	@RequestMapping(value = "/editForm1")
	public String editForm1(Long id, HttpServletRequest request) {
		Users admin;
		Role role = new Role();
		role.setCompanyId(getMe(request).getCompanyId());
		List<Role> list = roleService.findByModel(role);
		request.setAttribute("list", list);
		if (id != null) {
			admin = currentService.findById(id);
			request.setAttribute("obj", admin);
		}
		return "admin/shop1-form";
	}
	/**
	 * 二级代理商弹出框数据显示
	 */
	@RequestMapping(value = "/editForm2")
	public String editForm2(Long id, HttpServletRequest request) {
		Users admin;
		Role role = new Role();
		role.setCompanyId(getMe(request).getCompanyId());
		List<Role> list = roleService.findByModel(role);
		request.setAttribute("list", list);
		if (id != null) {
			admin = currentService.findById(id);
			request.setAttribute("obj", admin);
			request.setAttribute("u", currentService.findById(admin.getParentUserId()));
		}
		return "admin/shop2-form";
	}

	/**
	 * 跳转到修改个人信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/myinfo-list")
	public String myinfo(HttpServletRequest request) {
		request.setAttribute("obj", currentService.findById(getMe(request).getId()));
		return "admin/myinfo-form";
	}

	/**
	 * 进入修改密码界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/password")
	public String password(HttpServletRequest request) {
		request.setAttribute("obj", currentService.findById(getMe(request).getId()));
		return "admin/password-form";
	}

	/**
	 *修改密码 
	 */
	@RequestMapping(value = "/updatePassword")
	public @ResponseBody AjaxResult updatePassword(String password) {
		Users user = (Users) getSession().getAttribute("user");
		try {
			user.setPassword(EncrypUtil.getMD5(password));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return modify(currentService, user, "密码");
	}
	/**
	 * 所有销量统计数据显示
	 */
	@RequestMapping(value = "/qbxltjshowList")
	public @ResponseBody AjaxResult qbxltjshowList(HttpServletRequest request, Count count, PaginationVO pageVo) {
		List<Count> countList = countService.findAllStatistics(count, pageVo);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,countList , countService.findTotal(count));
	}
	
	/**
	 * 自己和下属代理商销量统计数据显示
	 */
	@RequestMapping(value = "/xltjshowList")
	public @ResponseBody AjaxResult xltjshowList(HttpServletRequest request,Count count, PaginationVO pageVo) {
		Users user = (Users) getSession().getAttribute("user");
		count.setUsersId(user.getId());
		count.setParentUserId(user.getId());
		List<Count> countList = countService.findMyStatistics(count, pageVo);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,countList , countService.findTotal(count));
	}
	/**
	 * 新增玩家统计数据显示
	 */
	@RequestMapping(value = "/addplayershowList")
	public @ResponseBody AjaxResult addplayerjshowList(HttpServletRequest request,String startTime,String endTime, PaginationVO pageVo) {
		List<Userdata> users = userdataService.findByModel(null);
		List<Userdata> userdataList = null;
		Userdata userdata = new Userdata();
		Long registertime = null;
		Date s=DateUtils.stringToDate(startTime, "yyyy-MM-dd");
		Date e=DateUtils.stringToDate(endTime, "yyyy-MM-dd");
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		for(int i=0;i<users.size();i++){
			registertime =(long)users.get(i).getRegistertime();
			int start = 0;
			int end = 0;
				if(startTime!=null&&!"".equals(startTime)){
					start = (int)(s.getTime()/1000);
				}
				if(endTime!=null&&!"".equals(endTime)){
					end = (int) (e.getTime()/1000);
				}
				userdata.setStartTime(start);
				userdata.setEndTime(end);
				userdataList = userdataService.findInPage(userdata, pageVo); 
			
		}
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,userdataList , userdataService.findTotal(userdata));
	}
	/**
	 * 流失玩家统计数据显示
	 */
	@RequestMapping(value = "/lossplayershowList")
	public @ResponseBody AjaxResult lossplayerjshowList(HttpServletRequest request, Userdata userdata, PaginationVO pageVo,int offLineTime) {
		List<Userdata> users = userdataService.findByModel(null);
		Long lastlogintime = null ;
		List<Userdata> userdataList = null;
		for(int i=0;i<users.size();i++){
			lastlogintime =(long)users.get(i).getLastlogintime();
			Date date = new Date();
			int time = (int)(date.getTime()/1000-2592000*offLineTime);
			userdata.setLastlogintime(time);
			userdataList = userdataService.findInPage(userdata, pageVo); 
		}
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,userdataList , userdataService.findTotal(userdata));
	}
}